//
//  ZQUserAccount.swift
//  新浪微博
//
//  Created by admin on 2020/6/1.
//  Copyright © 2020 huami. All rights reserved.
//

import UIKit

private let fileName: NSString = "useraccount.json"

@objcMembers
/// 用户账户信息
class ZQUserAccount: NSObject {
    /// 访问令牌
    var access_token: String? // = "2.00EahZ4Do5Q88D3b1354e0a73YOsXE"

    /// 用户代号
    var uid: String?
    /// access_token的生命周期，单位是秒数
    /// 开发者是5年
    /// 测试使用者是3天
    var expires_in: TimeInterval = 0 {
        didSet {
            expires_date = Date(timeIntervalSinceNow: expires_in)
        }
    }

    /// 过期日期演示
    var expires_date: Date?

    /// 用户昵称
    var screen_name: String?

    /// 用户头像
    var avatar_large: String?

    override init() {
        super.init()

        // 1.从沙盒读取数据
        guard let path = fileName.cz_appendDocumentDir(),
            let data = NSData(contentsOfFile: path),
            let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: Any] else {
            return
        }

        // 2.将数据转化为模型
        yy_modelSet(with: dict)

        print("从沙盒加载数据--\(self)")
        expires_date = Date(timeIntervalSinceNow: -3600 * 24)
//        print(expires_date)
        // 3.判断token是否过期
//        if expires_date?.compare(Date()) != .orderedDescending {
//            print("token过期")
//
//            access_token = nil
//            uid = nil
//           try? FileManager.default.removeItem(atPath: path)
//        }

        print("正常加载")

    }

    func saveAcount() {
        guard var dict = yy_modelToJSONObject() as? [String: Any] else {
            return
        }

        dict.removeValue(forKey: "expires_in")

        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            let filePath = fileName.cz_appendDocumentDir() else {
            return
        }

        (data as NSData).write(toFile: filePath, atomically: true)

        print("用户保存数据成功---\(filePath)")
    }

    override var description: String {
        return yy_modelDescription()
    }
}
